﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;

namespace Zocono.WCS.Domain.LogDomain
{
    public class InterfaceLogInfoService : IInterfaceLogInfoService
    {
        private readonly IInterfaceLogRepository _IInterfaceLogRepository;
        private readonly ISnowflake _Snowflake;
        private readonly ILogUtil _logUtil;
        public InterfaceLogInfoService(IInterfaceLogRepository interfaceLogRepository, ISnowflake snowflake, ILogUtil logUtil)
        {
            _IInterfaceLogRepository = interfaceLogRepository;
            _Snowflake = snowflake;
            _logUtil = logUtil;
        }
        public async Task<bool> AddInterfaceLogAsync(InterfaceLogInfo iterfaceLogInfo)
        {
            iterfaceLogInfo.ILogId = _Snowflake.GetId_RLogId();
            iterfaceLogInfo.CreateTime = DateTime.Now;
            bool flag = false;
            try
            {
                flag = await _IInterfaceLogRepository.InsertAsync(iterfaceLogInfo);
                _logUtil.Debug(JsonHelper.SerializeObject(iterfaceLogInfo));
                return true;
            }
            catch
            {
                return false;
            }

        }

        //public async Task<bool> AddInterfaceLogAsync(InterfaceLogInfo iterfaceLogInfo)
        //{
        //    // Key: ID, Value: 是否已使用
        //    Dictionary<long, bool> idCache = new Dictionary<long, bool>();
        //    bool isIdExist = true;
        //    long iLogId = 0;
        //    while (isIdExist)
        //    {
        //        // 先从缓存中获取ID
        //        if (idCache.Count > 0)
        //        {
        //            iLogId = idCache.FirstOrDefault(x => x.Value == false).Key;
        //            idCache[iLogId] = true;
        //        }
        //        else
        //        {
        //            // 生成新的ID
        //            iLogId = _Snowflake.GetId();
        //            idCache.Add(iLogId, true);
        //        }
        //        InterfaceLogInfo existingInterfaceLog = await _IInterfaceLogRepository.GetByIdAsync(iLogId);
        //        isIdExist = existingInterfaceLog != null;
        //        if (isIdExist)
        //        {
        //            // 标记ID已使用过
        //            idCache[iLogId] = true;
        //        }
        //    }
        //    iterfaceLogInfo.ILogId = iLogId;
        //    iterfaceLogInfo.CreateTime = DateTime.Now;
        //    bool flag = false;
        //    try
        //    {
        //        flag = await _IInterfaceLogRepository.InsertAsync(iterfaceLogInfo);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        // 记录异常日志
        //        _logUtil.Info("插入接口日志数据库失败");
        //        return false;
        //    }
        //}
        //public async Task<bool> AddInterfaceLogAsync(InterfaceLogInfo iterfaceLogInfo)
        //{

        //    iterfaceLogInfo.ILogId = _Snowflake.GetId();
        //    iterfaceLogInfo.CreateTime = DateTime.Now;
        //    bool flag = false;
        //    try
        //    {
        //        var exists = await _IInterfaceLogRepository.AsSugarClient().Queryable<InterfaceLogInfo>()
        //            .Where(it => it.InterfaceUrl == iterfaceLogInfo.InterfaceUrl
        //                   && it.ActionName == iterfaceLogInfo.ActionName
        //                   && it.InterfacePara == iterfaceLogInfo.InterfacePara
        //                   && it.InterfaceResult == iterfaceLogInfo.InterfaceResult)
        //            .AnyAsync();
        //        if (!exists)
        //        {
        //            flag = await _IInterfaceLogRepository.InsertAsync(iterfaceLogInfo);
        //        }
        //        else
        //        {
        //            flag = true;
        //        }
        //    }
        //    catch
        //    {
        //        _logUtil.Info("插入接口日志数据库失败");
        //        return false;
        //    }

        //    return flag;
        //}





        public async Task<PageDto<InterfaceLogInfoDto>> GetInterfaceLogAsync(InterfaceLogInfoDto iterfaceLogInfo)
        {
            PageModel page = new PageModel { PageIndex = iterfaceLogInfo.PageIndex, PageSize = iterfaceLogInfo.PageSize, };
            PageDto<InterfaceLogInfoDto> pageDto = new PageDto<InterfaceLogInfoDto>();
            RefAsync<int> totalNumber = 0;
            var exp = Expressionable.Create<InterfaceLogInfo>();
            exp.AndIF(!string.IsNullOrEmpty(iterfaceLogInfo.start), l => l.CreateTime >= iterfaceLogInfo.start.ToDateTimeFormat("yyyy-MM-dd HH:mm"));
            exp.AndIF(!string.IsNullOrEmpty(iterfaceLogInfo.end), l => l.CreateTime < iterfaceLogInfo.end.ToDateTimeFormat("yyyy-MM-dd HH:mm"));
            exp.AndIF(!string.IsNullOrEmpty(iterfaceLogInfo.Description), l => l.Description.Contains(iterfaceLogInfo.Description));
            exp.AndIF(!string.IsNullOrEmpty(iterfaceLogInfo.InterfaceUrl), l => l.InterfaceUrl.Contains(iterfaceLogInfo.InterfaceUrl));
            exp.AndIF(!string.IsNullOrEmpty(iterfaceLogInfo.InterfacePara), l => l.InterfacePara.Contains(iterfaceLogInfo.InterfacePara));
            exp.AndIF(!string.IsNullOrEmpty(iterfaceLogInfo.InterfaceResult), l => l.InterfaceResult.Contains(iterfaceLogInfo.InterfaceResult));
            var result = await _IInterfaceLogRepository.AsSugarClient().Queryable<InterfaceLogInfo>().Where(exp.ToExpression()).OrderBy(l=>l.CreateTime,OrderByType.Desc).Select(l => new InterfaceLogInfoDto
            {
                ILogId = l.ILogId,
                Description = l.Description,
                InterfaceUrl = l.InterfaceUrl,
                ActionName = l.ActionName,
                //IpAddress = l.IpAddress,
                InterfacePara = l.InterfacePara,
                InterfaceResult = l.InterfaceResult,
                IsSuccess = l.IsSuccess,
                StartTime = l.StartTime,
                EndTime = l.EndTime,
                CreateTime = l.CreateTime,

            }).ToPageListAsync(page.PageIndex, page.PageSize, totalNumber);
            pageDto.Result = result;
            pageDto.Total = totalNumber;
            return pageDto;
        }
    }
}
